package dnaUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class DnaReader {
	
	private String caminhoArquivo;
		
	public DnaReader() {
		this.caminhoArquivo = "C:/Bruna/Software Instalados/apache-tomcat-7.0.27/work/";
	}

	public String lerDNA(String arquivo){
		FileReader reader = null;		
		StringBuilder dna = new StringBuilder();
		try{
			try {
				arquivo = caminhoArquivo + arquivo;
				reader = new FileReader(arquivo);
				BufferedReader buff = new BufferedReader(reader);
				String linha;
				while( (linha = buff.readLine()) != null){
					System.out.print(linha);
					if(!validarDNA(linha)){
						System.out.print("DNA INVALIDO");
						return null;
					}
					dna.append(linha);
				}
				reader.close();
			} finally{
				if (reader != null) {
					reader.close();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dna.toString();	
	}
	
	public boolean validarDNA(String dna){		
		return dna.matches("^[CAGTacgt]+$");
	}
	
	public FileWriter exportarDNA(String dna, String nomeformatado){
		FileWriter arqDNA = null;
		try{			
			try {				
				arqDNA = new FileWriter(new File(caminhoArquivo+nomeformatado+"DNA.txt"));
				arqDNA.write(dna);
				arqDNA.close();
			} finally {
				if (arqDNA != null) {
					arqDNA.close(); 
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
		return arqDNA;
	}
}